import 'dart:async';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_sunmi_uvc_camera/flutter_sunmi_uvc_camera.dart';
import 'package:get/get.dart';
import 'package:google_mlkit_face_detection/google_mlkit_face_detection.dart';

class DemoController extends GetxController {
  static DemoController get find => Get.find();
  late UVCCameraController cameraController;
  DemoController();

  StreamSubscription<dynamic>? _listenCameraStream;

  final Rx<DetectedFace?> _detectedFace = Rx(null);
  DetectedFace? get detectedFace => _detectedFace.value;
  @override
  void onInit() {
    cameraController = UVCCameraController();
    super.onInit();
  }

  final Rx<Uint8List?> _imageBytes = Rx(null);
  Uint8List? get imageBytes => _imageBytes.value;
  // final convertNative = ConvertNativeImgStream();

  final FaceTaskDelegate _faceTaskDelegate = FaceTaskDelegate();

  bool _alreadyCheckingImage = false;
  bool _takePicture = false;
  Future<void> _takePictureFunc({
    required InputImage inputImage,
  }) async {
    try {
      if (_takePicture) {
        return;
      }
      _takePicture = true;
      final bytes =
          await _faceTaskDelegate.compressFaceImage(inputImage: inputImage);
      _imageBytes.value = bytes;
      _takePicture = false;
    } catch (e) {
      debugPrint('error--->$e');
      _takePicture = false;
    }
  }

  @override
  void onReady() {
    _listenCameraStream = cameraController.cameraStream.listen((image) async {
      try {
        if (_alreadyCheckingImage) {
          return;
        }
        _alreadyCheckingImage = true;
        _detectedFace.value = await FaceIdentifier.scanImage(
          cameraImage: image,
          performanceMode: FaceDetectorMode.fast,
        );
        if (detectedFace?.wellPositioned == true &&
            detectedFace?.isRealPerson == true) {
          _takePictureFunc(inputImage: image);
        }
        _alreadyCheckingImage = false;
      } catch (e) {
        debugPrint('error--->$e');
        _alreadyCheckingImage = false;
      }
    });

    super.onReady();
  }

  @override
  void onClose() {
    cameraController.dispose();
    _listenCameraStream?.cancel();
    super.onClose();
  }
}
